<?php
declare(strict_types=1);

namespace app\traits;

use Symfony\Polyfill\Uuid\Uuid;
use think\facade\Env;

/**
 * model 公共方法
 *
 * Class MyModelTrait
 * @package app\traits
 */
trait MyModelTrait
{
    static protected $Predis;
    // redis 过期时间 30 天
    static protected $redis_expire_seconds = 2592000;

    /**
     * 生成密码
     *
     * @param string $password
     * @param string $salt
     * @return string
     */
    public static function generatePassword(string $password, string $salt): string
    {
        return hash('sha256', $password.$salt, false);
    }// generatePassword() end

    /**
     * 生成 token
     *
     * @return string
     */
    public static function generateToken(): string
    {
        // 7af359ec-3922-40fc-be19-4f4455ac2905, 长度 36
        return Uuid::uuid_create();
    }// generateLog() end

    /**
     * 生成 token key
     *
     * @param string $token
     * @return string
     */
    public static function generateTokenKey(string $token): string
    {
        return substr($token, 0, 8).substr($token, -8, 8);
    }// generateTokenKey() end

    /**
     * vendor/predis/predis/src/ClientInterface.php 接口
     *
     * 获取 redis 实例
     * $client = self::generateRedisInstance();
     * $client->connect();
     * $client->setex('key', $seconds=3, 'value');
     * $client->get('key');
     * $client->disconnect();
     *
     * @return \Predis\Client
     */
    public static function generateRedisInstance()
    {
        // $client = new \Predis\Client('tcp://10.0.0.1:6379');
        if (self::$Predis instanceof \Predis\Client) return self::$Predis;

        $uri = "tcp://".Env::get('redis.host').':'.Env::get('port');
        return self::$Predis = new \Predis\Client($uri);
    }// generateRedisInstance() end

    /**
     * 生成密码盐
     *
     * @param int $length 长度
     * @return string
     */
    public static function generateSalt(int $length = 8)
    {
        $str      = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len      = strlen($str) - 1;
        $rand_str = '';

        for($i = 0; $i < $length; $i++){
            $num       = mt_rand(0, $len);
            $rand_str .= $str[$num];
        }

        return $rand_str;
    }// generateSalt() end

    /**
     * 获取搜索数据
     *
     * @param string $namespace  \app\model\ModelName::class
     * @param string $where       $where .= " AND field = :field";
     * @param array  $raw         $raw['field'] = "xxx";
     * @param int    $offset
     * @param int    $limit
     * @param array  $order
     * @return array
     */
    public static function searchForShow(
        string $namespace,
        string $where = "",
        array  $raw = [],
        int    $offset = 0,
        int    $limit = 10,
        array  $order = ['id', 'desc']
    ): array {
        // $where       .= " AND field = :field";
        // $raw['field'] = "xxx";
        // $where        = ltrim($where, " AND");

        $total = 0;
        $data  = [];
        if (class_exists($namespace) === false) return [$total, $data];

        $model = new $namespace();

        if (strlen($where) < 5 || empty($raw))
        {
            $total = $model->field('id')->count();
            $data  = $model->limit($offset, $limit)->order($order[0], $order[1])->select()->toArray();
        } else {
            $total = $model->whereRaw($where, $raw)->count('id');
            $data  = $model->whereRaw($where, $raw)->limit($offset, $limit)->order($order[0], $order[1])->select()->toArray();
        }
//        var_dump($model->getLastSql());

        return [$total, $data];
    }// searchForShow() end
}